<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-success"
          size="mini"
          :disabled="multiple"
          @click="handleCheck"
          v-hasPermi="['purchase:lqmCheck:check']"
        >
          审核
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-back"
          size="mini"
          :disabled="multiple"
          @click="handleBack"
          v-hasPermi="['purchase:lqmCheck:back']"
        >
          撤销审核
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="check_invalid = true"
          v-hasPermi="['purchase:lqmCheck:invalid']"
        >
          作废
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['purchase:lqmCheck:export']"
        >
          导出
        </el-button>
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      @scrollBottom="load"
      highlight-current-row
      border
      stripe
      v-loading="loading"
      :data="lqmMstrList"
      @row-click="clickRow"
      @selection-change="handleSelectionChange"
      :cell-style="iCellStyle"
      height="calc(100% - 300px)"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="#" width="40" type="index" align="center" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="请购单号"
        :show-overflow-tooltip="true"
        width="125"
        align="center"
        prop="lqmDjbh"
      />
      <el-table-column
        label="请购部门"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmBmdm"
      >
        <template v-slot="scope">
          <dict-tag :options="deptList" :value="scope.row.lqmBmdm" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="需求日期" :show-overflow-tooltip="true" align="center" prop="lqmXqrq" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lqmXqrq, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="品名规格"
        :show-overflow-tooltip="true"
        min-width="200"
        align="center"
        prop="lqmPmgg"
      />
      <el-table-column
        label="请购数量"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmQgsl"
      />
      <el-table-column
        label="单位"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmDw"
      >
        <template v-slot="scope">
          <dict-tag :options="unitOptions" :value="scope.row.lqmDw" />
        </template>
      </el-table-column>
      <el-table-column
        label="参考单价"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmCkdj"
      />
      <el-table-column
        label="备注"
        :show-overflow-tooltip="true"
        width="200"
        align="center"
        prop="lqmDesc"
      />
      <el-table-column
        label="订单状态"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmZtbzmc"
      />
      <el-table-column
        label="撤回原因"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmNgdesc"
      />
      <el-table-column
        label="建立人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmJlry"
      />
      <el-table-column
        label="建立日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="lqmJlrq"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.lqmJlrq, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmShry"
      />
      <el-table-column
        label="审核日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="lqmShrq"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.lqmShrq, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="批准人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="lqmPzry"
      />
      <el-table-column
        label="批准日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="lqmPzrq"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.lqmPzrq, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="物料代码"
        :show-overflow-tooltip="true"
        width="120"
        align="center"
        prop="lqmWldm"
      />
    </el-table>
    <div>
      <span>
        <img style="width: auto; height: 200px" :src="srcLqm" alt="" />
      </span>
    </div>

    <!-- 查询对话框   -->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="700px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="24">
          <el-form-item label="建立日期">
            <el-date-picker
              v-model="dateRange"
              size="small"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="请购单号">
            <el-input
              v-model="queryParams.lqmDjbh"
              placeholder="请输入请购单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 480px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="请购部门">
            <el-select
              placeholder="请选择请购部门"
              size="small"
              v-model="queryParams.lqmBmdm"
              style="width: 480px"
              clearable
            >
              <el-option
                v-for="item in deptList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="品名规格">
            <el-input
              v-model="queryParams.lqmPmgg"
              placeholder="请输入品名规格"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 480px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-radio-group v-model="queryParams.lqmZtbz">
              <el-radio label="1">未审核</el-radio>
              <el-radio label="2">已审核未批准</el-radio>
              <el-radio label="3">已审核已批准</el-radio>
              <el-radio label="4">采购中</el-radio>
              <el-radio label="5">已入库</el-radio>
              <el-radio label="-1">全部</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <!-- 作废 -->
    <Modal v-model="check_invalid" width="360" draggable scrollable>
      <p slot="header" style="color: #f60; text-align: center">
        <Icon type="ios-information-circle"></Icon>
        <span>确认作废？</span>
      </p>
      <div style="text-align: center">
        <p>确认要将此物料作废？一旦作废，该单据将永久失效，请谨慎操作！</p>
        <Input
          style="width: 80%"
          placeholder="作废理由"
          v-model="invalidReason"
        />
      </div>
      <div slot="footer">
        <Button type="error" size="large" long @click="handleInvalid"
          >作废</Button
        >
      </div>
    </Modal>
    <!-- 撤回 -->
    <Modal v-model="check_back" draggable scrollable width="300">
      <p slot="header" style="color: #f60; text-align: center">
        <Icon type="ios-information-circle"></Icon>
        <span>确认撤回？</span>
      </p>
      <div style="text-align: center">
        <p>撤回理由</p>
        <Input v-model="reson" style="width: 75%" />
      </div>
      <div slot="footer">
        <Button type="error" size="large" long @click="backLqm">撤回</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  listLqmMstr,
  checkLqmMstr,
  checkBackLqmMstr,
  invalidLqm,
  exportLqm,
} from "@/api/purchase/lqmMstr";
import { listDept } from "@/api/system/dept";
import { getImageByWldm } from "@/api/project/materiel";

export default {
  name: "LqmCheck",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 点击数据
      rowData: {},
      // 选中数据
      ids: [],
      clickData: [],
      check_back: false,
      reson: "",
      srcLqm: null,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      openSearch: false,
      // 总条数
      total: 0,
      // 零星请购单表格数据
      lqmMstrList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      check_invalid: false,
      // 作废原因
      invalidReason: null,
      // 建立日期时间范围
      dateRange: [
        new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 60),
        new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 60),
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        lqmDjbh: null,
        lqmZtbz: "-1",
        lqmPmgg: null,
        lqmJlrq: null,
      },
      queryParamsChild: {
        pageNum: 1,
        pageSize: 25,
        lqmPmgg: null,
      },
      // 表单参数
      form: {},
      // 产品筛选
      filterPmgg: null,
      // 筛选后的物料List
      selectedItmMstr: [],
      // 表单校验
      rules: {
        lqmDesc: [{ required: true, message: "用途不能为空", trigger: "blur" }],
        lqmWldm: [
          { required: true, message: "物料代码不能为空", trigger: "blur" },
        ],
        lqmQgsl: [
          { required: true, message: "请购数量不能为空", trigger: "blur" },
        ],
      },
      //单位字典
      unitOptions: [],
      //部门字典
      deptList: [],
    };
  },
  created() {
    //获取全部单位
    this.getAllDicts("sys_unit").then((response) => {
      this.unitOptions = response.data;
    });
    // 获取全部部门
    listDept({ parentId: 100 }).then((res) => {
      this.deptList = res.data;
      for (let item of this.deptList) {
        if (item.deptId !== 116) {
          item.dictLabel = item.deptName;
          item.listClass = "default";
          item.dictValue = item.deptId + "";
        } else {
          this.deptList.splice(this.deptList.indexOf(item), 1);
        }
      }
    });
    this.getList();
  },
  methods: {
    iCellStyle({ row, column, rowIndex, columnIndex }) {
      //审核状态
      if (row.lqmZtbz == "2") {
        return "color:#3399ff";
      }
      //批准状态
      else if (row.lqmZtbz == "4") {
        return "color:#bb0331";
      }
    },
    /** 查询零星请购单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.dateRange && "" != this.dateRange) {
        this.queryParams.params["beginLqmJlrq"] = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD 00:00:00");
        this.queryParams.params["endLqmJlrq"] = this.moment(
          this.dateRange[1]
        ).format("YYYY-MM-DD 23:59:59");
      }
      this.queryParams.pageNum = 1;
      listLqmMstr(this.queryParams).then((response) => {
        this.lqmMstrList = [];
        this.lqmMstrList = this.lqmMstrList.concat(response.rows);
        this.total = response.total;
        this.loading = false;
        this.rowData = null;
        this.clickRow(response.rows[0]);
      });
    },

    //load
    load() {
      if (
        this.queryParams.pageNum <
        Math.ceil(this.total / this.queryParams.pageSize)
      ) {
        this.queryParams.pageNum++;
        listLqmMstr(this.queryParams).then((response) => {
          this.lqmMstrList = this.lqmMstrList.concat(response.rows);
          this.total = response.total;
          this.loading = false;
        });
      }
      return 0;
    },
    load1() {
      if (
        this.queryParamsChild.pageNum <
        Math.ceil(this.total / this.queryParamsChild.pageSize)
      ) {
        this.queryParamsChild.pageNum++;
        listLqmMstr(this.queryParamsChild).then((response) => {
          this.selectedItmMstr = this.selectedItmMstr.concat(response.rows);
          this.total = response.total;
          this.loading = false;
        });
      }
      return 0;
    },
    // 取消按钮
    cancel() {
      this.openAdd = false;
      this.openEdit = false;
      this.openSearch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.filterPmgg = null;
      this.form = {
        lqmId: null,
        lqmDjbh: null,
        lqmBmdm: null,
        lqmXqrq: new Date(),
        lqmWldm: null,
        lqmDw: null,
        lqmwlpm: null,
        lqmwlgg: null,
        lqmPmgg: null,
        lqmQgsl: null,
        lqmCkdj: null,
        lqmKcsl: null,
        lqmZtbz: null,
        lqmFlag: null,
        lqmDesc: null,
        lqmNgdesc: null,
        lqmJlry: null,
        lqmJlrq: null,
        lqmShry: null,
        lqmShrq: null,
        lqmPzry: null,
        lqmPzrq: null,
        lqmQrry: null,
        lqmQrrq: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.lqmMstrList = [];
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.lqmId);
      this.clickData = selection;
      this.multiple = !selection.length;
    },
    // 选中数据
    clickRow(row) {
      this.rowData = row;
      this.single = row == null || row.lqmZtbz != 1 || row.lqmFlag != 0;
      if (row != null) {
        getImageByWldm(row.lqmWldm)
          .then((res) => {
            this.srcLqm = process.env.VUE_APP_BASE_API + res.msg;
          })
          .catch(() => {
            this.msgError("获取失败");
          });
      }
    },
    //验证是否存在
    isNotCheck(clickData, flag, ztbz) {
      for (let i of clickData) {
        if (i.lqmFlag == flag && i.lqmZtbz == ztbz) {
          return true;
        }
      }
      return false;
    },
    /** 审核按钮操作 */
    handleCheck() {
      const lqmIds = this.ids;
      //clickData
      if (!this.isNotCheck(this.clickData, 0, 1)) {
        this.msgError("请选择未审核的单据");
        return;
      }

      this.$confirm("确认要将选中单据通过审核?", "确认审核", {
        confirmButtonText: "审核",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(function () {
          return checkLqmMstr(lqmIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("审核成功");
        })
        .catch(() => {
          this.msgError("审核失败");
        });
    },
    /** 撤销按钮操作 */
    handleBack() {
      if (!this.isNotCheck(this.clickData, 0, 2)) {
        this.msgError("请选择单据状态:【审核】的单据");
        return;
      }
      this.check_back = true;
    },
    backLqm() {
      const lqmIds = this.ids;
      checkBackLqmMstr(lqmIds, this.reson).then((res) => {
        this.msgSuccess("撤回成功");
        this.check_back = false;
        this.getList();
      });
    },
    /** 作废按钮操作 */
    handleInvalid() {
      if (!this.isNotCheck(this.clickData, 0, 1)) {
        this.msgError("请选择单据状态:【审核】的单据");
        return;
      }
      invalidLqm(this.rowData.lqmId, this.invalidReason)
        .then((res) => {
          this.getList();
          this.check_invalid = false;
          this.invalidReason = null;
          this.msgSuccess("作废成功");
        })
        .catch(() => {
          this.msgError("作废失败");
        });
    },
    handleSearch() {
      this.reset();
      this.title = "查询零星请购单";
      this.openSearch = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportLqm(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped></style>
